<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'mobile' => ['required', 'exists:users,mobile'],
            'password' => ['required'],
        ], [
            'mobile' => '手机号不能为空',
            'mobile.exists' => '手机号不存在',
            'password.required' => '密码不能为空',
        ]);
        $isLogin = Auth::attempt([
            "mobile" => $request->mobile,
            'password' => $request->password
        ], $request->remember ?? true);
        if ($isLogin) {
            $user = Auth::user();
            return $this->success("登录成功",
                [
                    'user' => $user,
                    'token' => $user->createToken('login')->plainTextToken,
                ]);
        }

        return response(['message' => '帐号或密码错误'], 405);
    }

    /**
     * 退出登录
     * @return void
     * @throws RuntimeException
     * @throws Exception
     * @throws BindingResolutionException
     */
    public function logout()
    {
        //退出登录
        Auth::user()->tokens()->delete();
        return $this->success('帐号退出成功');
    }

    /**
     * 获取令牌
     *
     * @param User $user
     * @return void
     */
    protected function token(User $user)
    {
        return $user->createToken('auth')->plainTextToken;
    }

    /**
     * 找回密码
     *
     * @param Request $request
     * @return void
     */
    public function forget(Request $request, User $user)
    {
        $request->validate([
            'mobile' => ['required','exists:users,'],
            'password' => ['required', 'confirmed', 'between:5,20'],
        ], [
            'mobile.required' => '帐号不能为空',
            'mobile.exists' => '帐号不存在',
            'password.required' => '密码不能为空',
        ]);

        $user = User::where("mobile", $request->mobile)->first();
        $user->password = Hash::make($request->password);
        $user->save();
        return ['message' => '密码重置成功', 'token' => $this->token($user)];
    }
}
